#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/12/29 13:02
    Desc  :
--------------------------------------
"""
import datetime
import io
import random

import xlwt

from common.exceptions import MicroseerDemandIsNotStart
from common.tools.CommonRequestsClient import PostRequestClient, GetRequestClient
from common.tools.ExcelExportClient import ExcelClient
from common.utils.log_utils import logger
from common.utils.random_utils import random_name, random_ssn, random_phone
from extends import yamlUtils
from extends.microseer.Vo.queryDemandGapListVo import QueryDemandGapListVo
from extends.microseer.Vo.queryDemandListVo import QueryDemandListVo
from extends.microseer.login.decorator import login_auth_moa
import extends.microseer.login.decorator as decorator


@login_auth_moa()
def get_demand_info(demandId, **kwargs):
    """生成候选人表格"""
    decorator.set_env(kwargs.get('env'))
    decorator.set_mscid(kwargs.get('mscid'))
    recruit_url = yamlUtils.get(decorator.get_env()).get('recruit').get('url')

    path = f'/roster/weizhi/recruit/demand/baseInfo/detail/{demandId}'

    getRequestUtils = GetRequestClient()

    getRequestUtils.headers = decorator.get_headers()
    getRequestUtils.url = recruit_url + path

    res = getRequestUtils.result().json()

    companyName = res.get('data').get('extra').get('demand').get('companyName')
    demandName = res.get('data').get('extra').get('demand').get('demandName')
    status = res.get('data').get('extra').get('demand').get('status')

    if status != 20:
        raise MicroseerDemandIsNotStart(f"订单:demandId={demandId}未启用")

    data: dict = res.get('data').get('extra').get('demand')

    orderCode = get_demand_code(demandName = demandName,
                                companyName = companyName,
                                demandId = demandId, **kwargs)

    data['orderCode'] = orderCode

    logger.info(data)

    return data


@login_auth_moa()
def get_demand_code(**kwargs):
    """获取订单编号"""
    decorator.set_env(kwargs.get('env'))
    decorator.set_mscid(kwargs.get('mscid'))
    recruit_url = yamlUtils.get(decorator.get_env()).get('recruit').get('url')
    path = '/roster/weizhi/recruit/demand/pageList'
    queryDemandListVo = QueryDemandListVo()

    queryDemandListVo.demandName = kwargs.get('demandName')
    queryDemandListVo.companyName = kwargs.get('companyName')
    queryDemandListVo.pageSize = 10

    postRequestClient = PostRequestClient()

    postRequestClient.headers = decorator.get_headers()

    postRequestClient.url = recruit_url + path

    postRequestClient.body = queryDemandListVo.__dict__

    res = postRequestClient.result().json()

    records = res.get('data').get('records')

    if records:
        for i in records:
            if int(i.get('demandId')) == int(kwargs.get('demandId')):
                return i.get('orderCode')
            else:
                return None
    else:
        return None


@login_auth_moa()
def get_demand_gap_info(demandId, **kwargs):
    """
    获取订单缺口信息
    :param demandId:
    :return:
    """
    decorator.set_env(kwargs.get('env'))
    decorator.set_mscid(kwargs.get('mscid'))
    recruit_url = yamlUtils.get(decorator.get_env()).get('recruit').get('url')
    path = '/roster/weizhi/recruit/demand/selectRecruitDemandGapList'

    queryDemandGapListVo = QueryDemandGapListVo()

    queryDemandGapListVo.demandId = demandId
    queryDemandGapListVo.pageSize = 5
    postRequestClient = PostRequestClient()
    postRequestClient.headers = decorator.get_headers()

    postRequestClient.url = recruit_url + path
    postRequestClient.body = queryDemandGapListVo.__dict__

    res = postRequestClient.result().json()
    records = res.get('data').get('records')
    if records:
        return records[random.randint(0, len(records))] if len(records) != 1 else records[0]
    else:
        return None


def candidate_import_excel(demandId: int, num: int, **kwargs):
    """
    生成候选人导入excel
    :param demandId:
    :param num:
    :return:
    """
    excel_item = [
        '企业名称',
        '需求名称',
        '订单编号',
        '姓名',
        '身份证',
        '联系电话',
        '性别',
        '年龄',
        '招聘渠道',
        '推送人',
        '出生日期',
        '面试日期',
        '面试时间',
        '电子邮箱',
        '用工身份',
    ]
    excelClient = ExcelClient()
    excelClient.excel_headers = excel_item
    decorator.set_env(kwargs.get('env'))
    decorator.set_mscid(kwargs.get('mscid'))
    demandInfo: dict = get_demand_info(demandId = demandId, **kwargs)

    for i in range(len(excelClient.excel_headers)):
        excelClient.sheet.write(0, i, excelClient.excel_headers[i])
    for i in range(1, num + 1):

        for j in range(0, len(excelClient.excel_headers)):
            if excelClient.excel_headers[j] == '企业名称':
                excelClient.sheet.write(i, j, demandInfo.get('companyName'))
            elif excelClient.excel_headers[j] == '需求名称':
                excelClient.sheet.write(i, j, demandInfo.get('demandName'))
            elif excelClient.excel_headers[j] == '订单编号':
                excelClient.sheet.write(i, j, demandInfo.get('orderCode'))
            elif excelClient.excel_headers[j] == '姓名' or excelClient.excel_headers[j] == '名称':
                excelClient.sheet.write(i, j, f'测试{random_name()}二要素')
            elif excelClient.excel_headers[j] == '身份证号' or excelClient.excel_headers[j] == '身份证' or \
                    excelClient.excel_headers[j] == '身份证号码':
                excelClient.sheet.write(i, j, random_ssn())
            elif excelClient.excel_headers[j] == '手机号' or excelClient.excel_headers[j] == '联系方式' or \
                    excelClient.excel_headers[j] == '联系电话' or excelClient.excel_headers[j] == '手机号码':
                excelClient.sheet.write(i, j, random_phone())
            elif excelClient.excel_headers[j] == '性别':
                excelClient.sheet.write(i, j, random.choice(['男', '女']))
            elif excelClient.excel_headers[j] == '招聘渠道':
                excelClient.sheet.write(i, j, '自招')
            elif excelClient.excel_headers[j] == '年齡':
                excelClient.sheet.write(i, j, random.randint(20, 50))
            else:
                excelClient.sheet.write(i, j, '')

    output = io.BytesIO()
    excelClient.wb.save(output)
    output.seek(0)
    return output


def push_person_info_import_excel(demandId: int, num: int, **kwargs):
    """
    人员推送导入模板
    :param demandId:
    :param num:
    :param kwargs:
    :return:
    """
    excel_item = [
        '姓名',
        '身份证',
        '手机号',
        '上班地点',
        '面试日期',
        '面试时间',
    ]

    excelClient = ExcelClient()
    excelClient.excel_headers = excel_item
    decorator.set_env(kwargs.get('env'))
    decorator.set_mscid(kwargs.get('mscid'))
    gapInfo: dict = get_demand_gap_info(demandId = demandId, env = kwargs.get('env'))

    for i in range(len(excelClient.excel_headers)):
        excelClient.sheet.write(0, i, excelClient.excel_headers[i])
    for i in range(1, num + 1):

        for j in range(0, len(excelClient.excel_headers)):
            if excelClient.excel_headers[j] == '姓名' or excelClient.excel_headers[j] == '名称':
                excelClient.sheet.write(i, j, f'测试{random_name()}二要素')
            elif excelClient.excel_headers[j] == '身份证号' or excelClient.excel_headers[j] == '身份证' or \
                    excelClient.excel_headers[j] == '身份证号码':
                excelClient.sheet.write(i, j, random_ssn())
            elif excelClient.excel_headers[j] == '手机号' or excelClient.excel_headers[j] == '联系方式' or \
                    excelClient.excel_headers[j] == '联系电话' or excelClient.excel_headers[j] == '手机号码':
                excelClient.sheet.write(i, j, random_phone())
            elif excelClient.excel_headers[j] == '上班地点':
                excelClient.sheet.write(i, j, gapInfo.get('outlet'))
            elif excelClient.excel_headers[j] == '面试日期':
                excelClient.sheet.write(i, j, f"{datetime.datetime.now().strftime('%Y-%m-%d')}")
            elif excelClient.excel_headers[j] == '面试时间':
                excelClient.sheet.write(i, j, f"{datetime.datetime.now().strftime('%H')}:00")
            else:
                excelClient.sheet.write(i, j, '')

    output = io.BytesIO()
    excelClient.wb.save(output)
    output.seek(0)
    return output


def person_barch_import_excel(num: int, **kwargs):
    """
    人才库导入
    :param num: 数量
    :param kwargs:
    :return:
    """

    excel_item = [
        '招聘渠道',
        '供应商名称',
        '姓名',
        '手机号',
        '身份证',
        '人员来源',
        '性别',
        '年龄',
        '期望行业',
        '期望岗位',
        '期望工作地(城市)',
        '期望工作地((区/县)',
        '期望薪资',
        '健康证',
        '学历',
        '工作经验',
        '特殊技能',
        '联系地址',
        '求职类型',
        '银行卡号',
        '开户银行',
        '电子邮箱',
        '紧急联系人关系',
        '紧急联系人',
        '紧急联系人电话',
        '紧急联系人地址',
        '毕业学校',
        '专业名称',
        '吃住情况',
        '休假情况',
        '倒班情况',
        '兼职时间',
        '企业福利',
        '兼职身份',
        '自我评价',
    ]

    employeeSource = [
        '58同城',
        'BOSS直聘',
        '前程无忧',
        '智联招聘',
        '拉勾网',
        '猎聘网',
        '赶集网',
        '大街网',
        '中华英才网',
        '其他',

    ]

    excelClient = ExcelClient()
    excelClient.excel_headers = excel_item
    decorator.set_env(kwargs.get('env'))
    decorator.set_mscid(kwargs.get('mscid'))

    for i in range(len(excelClient.excel_headers)):
        excelClient.sheet.write(0, i, excelClient.excel_headers[i])
    for i in range(1, num + 1):

        for j in range(0, len(excelClient.excel_headers)):
            if excelClient.excel_headers[j] == '姓名' or excelClient.excel_headers[j] == '名称':
                excelClient.sheet.write(i, j, f'测试{random_name()}二要素')
            elif excelClient.excel_headers[j] == '身份证号' or excelClient.excel_headers[j] == '身份证' or \
                    excelClient.excel_headers[j] == '身份证号码':
                excelClient.sheet.write(i, j, random_ssn())
            elif excelClient.excel_headers[j] == '手机号' or excelClient.excel_headers[j] == '联系方式' or \
                    excelClient.excel_headers[j] == '联系电话' or excelClient.excel_headers[j] == '手机号码':
                excelClient.sheet.write(i, j, random_phone())
            elif excelClient.excel_headers[j] == '人员来源':
                excelClient.sheet.write(i, j, random.choice(employeeSource))
            elif excelClient.excel_headers[j] == '招聘渠道':
                excelClient.sheet.write(i, j, random.choice(['自招', '供应商']))
            elif excelClient.excel_headers[j] == '性别':
                excelClient.sheet.write(i, j, random.choice(['男', '女']))
            elif excelClient.excel_headers[j] == '年龄':
                excelClient.sheet.write(i, j, random.randint(20, 60))
            else:
                excelClient.sheet.write(i, j, '')

    output = io.BytesIO()
    excelClient.wb.save(output)
    output.seek(0)
    return output
